<template>
  <div class="detail">
    <div class="title">
      <div class="price">
        <span>¥ {{ house.month_rent }}/月</span>
      </div>
      <div class="info">
        <h1>{{ house.title }}</h1>
        <p><i class="el-icon-map-location"></i> {{ house.address }}</p>
      </div>
    </div>
    
    <el-carousel :interval="3000" type="card" height="500px" class="carousel">
      <el-carousel-item v-for="item in house.img_url" :key="item">
        <img :src="item" alt="">
      </el-carousel-item>
    </el-carousel>
    
    <div class="main">
      <div class="left">
        <div class="descriptions">
          <el-descriptions title="房子详细信息" border>
            <el-descriptions-item label="状态">{{ houseStatus }}</el-descriptions-item>
            <el-descriptions-item label="租金">¥{{ house.month_rent }}/月</el-descriptions-item>
            <el-descriptions-item label="押金">¥1000</el-descriptions-item>
            <el-descriptions-item label="租赁方式">{{ house.rent_type === 'whole' ? '整租' : '合租' }}</el-descriptions-item>
            <el-descriptions-item label="房产证编号">{{ house.certificate }}</el-descriptions-item>
            <el-descriptions-item label="卧室数量">{{ house.bedroom }}</el-descriptions-item>
            <el-descriptions-item label="卫生间数量">{{ house.toilet }}</el-descriptions-item>
            <el-descriptions-item label="厨房数量">{{ house.kichen }}</el-descriptions-item>
            <el-descriptions-item label="客厅数量">{{ house.toilet }}</el-descriptions-item>
            <el-descriptions-item label="房间面积">{{ house.area }} ㎡</el-descriptions-item>
            <el-descriptions-item label="是否有空调">{{ house.conditioner ? '有空调' : '没有空调' }}</el-descriptions-item>
            <el-descriptions-item label="建成年份">{{ house.buildyear }}</el-descriptions-item>
            <el-descriptions-item label="朝向">朝{{ house.direction }}</el-descriptions-item>
            <el-descriptions-item label="楼层">{{ house.floor }}/{{ house.maxfloor }}</el-descriptions-item>
            <el-descriptions-item label="是否有电梯">{{ house.elevator ? '有电梯' : '没有电梯' }}</el-descriptions-item>
            <el-descriptions-item label="联系人姓名">{{ house.contact_name }}</el-descriptions-item>
            <el-descriptions-item label="联系人手机号">{{ house.contact_phone }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="desc">
          <h2>详细描述</h2>
          <div class="content">{{ house.content }}</div>
        </div>
        
        <div class="container">
          <h2>地图位置</h2>
          <div class="map" id="map"></div>
        </div>
        
        <div class="gallery">
          <h2>房屋相册</h2>
          <div class="imgs">
            <el-image 
              style="width: 33.33%; height: 180px; padding: 5px;" 
              v-for="item in house.img_url" 
              :key="item"
              :src="item" 
              :preview-src-list="house.img_url"
              fit="cover"
              lazy>
            </el-image>
          </div>
        </div>
      </div>
      
      <div class="right">
        <div class="collect" v-if="house.status === 1">
          <i @click="collect" :class="[isStar ? 'el-icon-star-on star' : 'el-icon-star-off']"> 
            {{ isStar ? '已收藏' : '收藏' }}
          </i>
        </div>
        
        <div class="date" v-if="house.status === 1">
          <div class="price">¥ {{ (house.month_rent / 30).toFixed(2) }} /日</div>
          <div class="pick">
            <p>选择日期下单预定，入住时间和退租时间</p>
            <el-date-picker 
              v-model="date" 
              type="daterange" 
              range-separator="至" 
              start-placeholder="开始日期"
              end-placeholder="结束日期" 
              :default-time="[formatDate]" 
              :picker-options="pickerOptions"
              style="width: 100%;">
            </el-date-picker>
            <el-button type="primary" class="btn2" @click="timeBtn">立即预定</el-button>
          </div>
        </div>
        
        <div class="contact" v-if="house.contact_name">
          <h2>联系房东</h2>
          <div class="msg">
            <el-avatar :size="80" :src="defaultavatar" class="imgtx" />
            <h3>{{ house.contact_name }}</h3>
            <p>{{ house.contact_phone }}</p>
            <img src="@/assets/wxqr.jpg" alt="扫一扫添加微信" class="imgewm" />
            <p class="wz">扫一扫上面的二维码图案，加我为朋友</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Detail',
  created() {
    this.getHouseInfo()
  },
  data() {
    return {
      date: '',
      defaultavatar: require('@/assets/user.png'),
      house: [],
      currentDate: new Date(),
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    init() {
      if (!this.house.longitude_latitude) return;
      
      var coordinates = this.house.longitude_latitude.split(',').map(Number)
      var myLatlng = new qq.maps.LatLng(coordinates[0], coordinates[1])
      var myOptions = {
        zoom: 16,
        center: myLatlng,
        mapTypeId: qq.maps.MapTypeId.ROADMAP,
      }
      var map = new qq.maps.Map(document.getElementById('map'), myOptions)
      
      var marker = new qq.maps.Marker({
        position: myLatlng,
        map: map,
      })
      
      var infoWindow = new qq.maps.InfoWindow({
        content: `<div style="padding:10px;">${this.house.address}</div>`
      });
      
      qq.maps.event.addListener(marker, 'click', () => {
        infoWindow.open(map, marker);
      });
    },

    async timeBtn() {
      if (!this.$store.getters.getUserInfo) {
        return this.$message({
          message: '请先登录',
          type: 'warning'
        })
      }
      
      if (!this.$store.getters.getUserInfo?.idcard) {
        return this.$alert('个人信息未完善，需完善后才能租房', '提示', {
          confirmButtonText: '去完善',
          callback: action => {
            this.$router.push({ path: '/index/admin/info' })
          }
        });
      }
      
      if (this.$store.getters.getUserInfo?.role != 'customer') {
        return this.$message({
          message: '只有租客账号才能预定房屋',
          type: 'warning'
        })
      }
      
      if (!this.date || this.date.length < 2) {
        return this.$message({
          type: 'warning',
          message: '请选择入住时间',
        })
      }
      
      let formattedDates = this.date.map((d) => {
        let date = new Date(d)
        return (
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1).toString().padStart(2, '0') +
          '-' +
          date.getDate().toString().padStart(2, '0')
        )
      })
      
      if (!this.isNowDateValid()) {
        this.date = ''
        return this.$message({
          type: 'warning',
          message: '请选择有效的入住时间',
        })
      }
      
      const orderInfo = {
        houseid: this.house.id,
        customerid: this.$store.getters.getUserInfo.id,
        ownerid: this.house.owner_id,
        status: -2,
        daynum: this.calculateRentDays(formattedDates[0], formattedDates[1]),
        startdate: formattedDates[0],
        enddate: formattedDates[1],
        monthrent: this.house.month_rent,
        totalamount: (this.calculateRentDays(formattedDates[0], formattedDates[1]) * (this.house.month_rent / 30).toFixed(2) + 1000),
      }
      
      const { data: res } = await this.$axios.post('/api/order/add', orderInfo)
      if (res.status !== 200) {
        return this.$message({
          type: 'warning',
          message: res.message,
        })
      }
      
      this.$alert('请签约合同，点击确认前往合同页，取消请点右上角', '订单创建成功', {
        confirmButtonText: '确定',
        callback: (action) => {
          if (action === 'confirm') {
            this.$router.push({ path: '/index/agreement', query: { orderNo: res.data.order_number } });
          }
        },
      })
    },
    
    async getHouseInfo() {
      const id = this.$route.params.id;
      const { data: res } = await this.$axios.get(`/api/house/${id}`)
      if (res.status === 200) {
        this.house = res.data
        this.getOwner()
        this.$nextTick(() => {
          this.init()
        })
      }
    },
    
    async getOwner() {
      const { data: res } = await this.$axios.get(`/api/user/info/${this.house.owner_id}`)
      if (res.status === 200 && res.data.avatar) {
        this.defaultavatar = res.data.avatar
      }
    },
    
    async collect() {
      if (!this.$store.getters.getUserInfo) {
        return this.$message({
          message: '请先登录',
          type: 'warning'
        })
      }
      
      if (this.$store.getters.getUserInfo?.role != 'customer') {
        return this.$message({
          message: '只有租客账号才能收藏房屋',
          type: 'warning'
        })
      }
      
      if (this.isStar) {
        const id = this.$store.getters.getcollectList?.find(my => my.house_id === this.house.id).id
        const { data: res } = await this.$axios.get(`/api/collect/delete/${id}`)
        await this.$store.dispatch('collectInit', this.$store.getters.getUserInfo.id)
        if (res.status === 200) {
          this.$message({
            message: '取消收藏成功',
            type: 'success'
          })
        }
      } else {
        const info = {
          userid: this.$store.getters.getUserInfo.id,
          houseid: this.house.id,
          title: this.house.title,
          address: this.house.address,
          monthrent: this.house.month_rent,
          img: this.house.img_url[0]
        }
        const { data: res } = await this.$axios.post('/api/collect/add', info)
        await this.$store.dispatch('collectInit', this.$store.getters.getUserInfo.id)
        if (res.status === 200) {
          this.$message({
            message: '收藏成功',
            type: 'success'
          })
        }
      }
    },
    
    isNowDateValid() {
      return this.date[0] >= this.currentDate
    },
    
    calculateRentDays(start, end) {
      let startDate = new Date(start);
      let endDate = new Date(end);
      let differenceInTime = endDate.getTime() - startDate.getTime();
      let differenceInDays = differenceInTime / (1000 * 3600 * 24);
      return Math.ceil(differenceInDays) + 1;
    }
  },
  computed: {
    houseStatus() {
      switch (this.house.status) {
        case 1: return '未租出';
        case 2: return '已租出';
        case 3: return '已下架';
        case -2: return '待审核';
        case -3: return '审核不通过';
        default: return '未知状态';
      }
    },
    
    formatDate() {
      let date = new Date(this.currentDate.getTime() + 5000);
      let hours = date.getHours().toString().padStart(2, '0');
      let minutes = date.getMinutes().toString().padStart(2, '0');
      let seconds = date.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    },
    
    isStar() {
      return this.$store.getters.getcollectList?.some(item => item.house_id === this.house.id)
    }
  }
}
</script>

<style scoped>
.detail {
  padding: 20px 0;
  background-color: #f8f9fe;
  max-width: 1400px;
  margin: 0 auto;
}

.title {
  padding: 40px 0;
  text-align: center;
}

.title .price {
  font-size: 36px;
  color: #ff4d4f;
  font-weight: bold;
}

.info h1 {
  font-size: 32px;
  color: #1a1a1a;
  margin: 15px 0;
  line-height: 1.3;
}

.info p {
  color: #666;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info i {
  margin-right: 8px;
}

.carousel {
  margin: 0 auto;
  max-width: 1200px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.carousel img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.main {
  padding: 0 5%;
  display: flex;
  justify-content: space-between;
  gap: 30px;
  margin-top: 30px;
}

.main .left {
  flex: 1;
  min-width: 0;
}

.main .right {
  width: 380px;
  position: sticky;
  top: 20px;
  align-self: flex-start;
}

.descriptions {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.desc {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.desc h2 {
  font-size: 20px;
  color: #1a1a1a;
  margin-bottom: 16px;
  font-weight: 600;
}

.desc .content {
  color: #666;
  line-height: 1.8;
  white-space: pre-line;
}

.container {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.container h2 {
  font-size: 20px;
  color: #1a1a1a;
  margin-bottom: 16px;
  font-weight: 600;
}

.map {
  height: 400px;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 16px;
}

.gallery {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.gallery h2 {
  font-size: 20px;
  color: #1a1a1a;
  margin-bottom: 16px;
  font-weight: 600;
}

.imgs {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -5px;
}

.imgs .el-image {
  transition: all 0.3s;
}

.imgs .el-image:hover {
  transform: translateY(-3px);
}

.collect {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  text-align: center;
}

.el-icon-star-off,
.el-icon-star-on {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 24px;
  height: 48px;
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

.el-icon-star-off:hover {
  background: rgba(255, 77, 79, 0.2);
}

.el-icon-star-on {
  background: #ff4d4f !important;
  color: white !important;
}

.date {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 24px;
}

.date .price {
  background: linear-gradient(135deg, #4b5fff, #6c5ce7);
  padding: 20px;
  color: white;
  font-size: 22px;
  font-weight: 600;
  text-align: center;
}

.date .pick {
  padding: 24px;
}

.date .pick p {
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
  text-align: center;
}

.btn2 {
  width: 100%;
  height: 48px;
  margin-top: 24px;
  background: linear-gradient(135deg, #4b5fff, #6c5ce7);
  border: none;
  font-size: 16px;
  transition: all 0.3s;
}

.btn2:hover {
  opacity: 0.9;
  transform: translateY(-2px);
}

.contact {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.contact h2 {
  padding: 16px;
  background: linear-gradient(135deg, #4b5fff, #6c5ce7);
  color: white;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
}

.msg {
  padding: 24px;
  text-align: center;
}

.imgtx {
  margin: 0 auto 16px;
  border: 2px solid #f0f0f0;
}

.msg h3 {
  font-size: 18px;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.msg p {
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
}

.imgewm {
  width: 200px;
  height: 200px;
  margin: 16px auto;
  display: block;
  border: 1px solid #f0f0f0;
}

.wz {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

@media (max-width: 1200px) {
  .main {
    flex-direction: column;
  }
  
  .main .right {
    width: 100%;
    position: static;
    margin-top: 40px;
  }
}

@media (max-width: 768px) {
  .title .price {
    font-size: 28px;
  }
  
  .info h1 {
    font-size: 24px;
  }
  
  .carousel {
    height: 300px !important;
  }
  
  .main {
    padding: 0 15px;
  }
  
  .map {
    height: 300px;
  }
  
  .imgs .el-image {
    width: 50% !important;
    height: 150px !important;
  }
}
</style>